package com.harmontronics.hanma.paas.paas.config;

import com.harmontronics.hanma.paas.paas.config.xss.EscapeUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;


/**
 * XSS过滤处理
 *
 * @author ruoyi
 */
public class AppUniqueHttpServletRequest extends HttpServletRequestWrapper {
    public static final String APP_UNIQUE="App-Unique";
    /**
     * @param request
     */
    public AppUniqueHttpServletRequest(HttpServletRequest request) {
        super(request);
        //参数传递unique
       String appUnique =  request.getParameter(APP_UNIQUE);
       if(appUnique == null){
           String referer = request.getHeader("Referer");
           if(referer != null && referer.indexOf(APP_UNIQUE) > -1){
               String tmp = referer.substring(referer.indexOf(APP_UNIQUE));
               if(tmp.indexOf("&") > -1){
                   tmp = tmp.substring(0,tmp.indexOf("&"));
               }
               appUnique = tmp.replace(APP_UNIQUE+"=","");
           }
       }

       if(!ObjectUtils.isEmpty(appUnique)&&request.getHeader(APP_UNIQUE)==null){
           addHeader(APP_UNIQUE,appUnique);
       }

    }

    private Map<String, String> headerMap = new HashMap<>();

    public void addHeader(String name, String value) {
        this.headerMap.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        String headerValue = super.getHeader(name);
        if (this.headerMap.containsKey(name)) {
            headerValue = this.headerMap.get(name);
        }
        return headerValue;
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        for (String name : this.headerMap.keySet()) {
            names.add(name);
        }
        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> values = Collections.list(super.getHeaders(name));
        if (this.headerMap.containsKey(name)) {
            values = Arrays.asList(this.headerMap.get(name));
        }
        return Collections.enumeration(values);
    }

}
